/*
 * Copyright (C) 2017 Fromentin Xavier
 *
 * This file is part of GDOB.
 *
 * GDOB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GDOB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.grimdawnofflinebuilder.util.tex

import com.grimdawnofflinebuilder.util.tex.DDSReader.*
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.system.measureTimeMillis

/**
 * Class to convert tex file to png to be able to use them in the UI
 */
class TexConverter {

    /**
     * Converts a .tex fl to a .png
     *
     * @param file the file to convert
     */
    fun convertTexToPng( file: File) {
        println( "Converting file : $file" )
        val ddsFile = File( "${file.absolutePath}.dds" )
        val pngFile = File( file.absolutePath.replace( ".tex", ".png") )

        // Convert from tex to dds
        val ddsTime = measureTimeMillis {
            val processBuilder = ProcessBuilder( "util/TQ.Texture.Extract.exe", file.absolutePath )
            val process = processBuilder.start()
            val exitValue = process.waitFor()
            if( exitValue != 0 )
                println( "An error occurred while converting tex file to dds format")
            if( !ddsFile.isFile )
                println( "The dds file from conversion does not exist !" )
        }
        println( "Conversion to dds took ${ddsTime / 1000} seconds" )

        // Convert from dds to png
        val pngTime = measureTimeMillis {
            // Read bytes
            val fis = ddsFile.inputStream()
            val buffer = ByteArray(fis.available())
            fis.read(buffer)
            fis.close()

            // Read dds data
            val pixels = read(buffer, ARGB, 0)
            val width = getWidth(buffer)
            val height = getHeight(buffer)

            // Create png image
            val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
            image.setRGB(0, 0, width, height, pixels, 0, width)

            ImageIO.write(image, "PNG", pngFile )
            if( !pngFile.isFile )
                println( "The png file from conversion does not exist !" )
        }
        println( "Conversion to png took ${pngTime / 1000} seconds" )
        println( "Cleaning up dds file...")
        cleanup( ddsFile )
        println( "DDS file cleaned up !")
    }

    /**
     * Clean up the given file
     *
     * @param file file to remove
     */
    private fun cleanup( file: File) {
        file.delete()
    }

}

fun main( args: Array<String> ) {
    val dir = File( """C:\Users\zert\Desktop\GrimDawnDatas\items\gearfeet\bitmaps""" )
    val totalTime = measureTimeMillis {
        dir.listFiles { file -> file.extension == "tex" }
          .forEach { TexConverter().convertTexToPng(it) }
    }
    println( "Total time : ${totalTime / 1000} seconds" )
}